<template>
	<div class="role_container">
		<div class="role_section">
			<!-- 头部--搜索添加 -->
			<div class="role_header">
				<el-input clearable v-model="searchVal" style="width: 200px;" placeholder="请输入管理员名称" />
				<el-button type="primary" icon="el-icon-search" @click='search()' style="margin-left: 6px;">查找</el-button>
				<el-button type="primary" icon="el-icon-edit" @click='fixAdmin("add")'>添加</el-button>
			</div>
			<el-table :data='adminList' size="small" v-loading="loading" element-loading-text="正在查询中。。。" border fit
			 highlight-current-row>
				<el-table-column align="center" label="管理员ID" prop="id" sortable />
				<el-table-column align="center" label="管理员名称" prop="username" />
				<el-table-column align="center" label="管理员头像" prop="avatar" />
				<el-table-column align="center" label="管理员角色" prop="roleIds">
					<template slot-scope="scope">
						<el-tag v-for="roleId in scope.row.roleIds" :key="roleId" type="primary" style="margin-right: 20px;">{{ getRole(roleId) }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column align="center" label="操作" class-name="small-padding fixed-width">
					<template slot-scope="scope">
						<el-button type="primary" size="mini" @click='fixAdmin("edit",scope.row)'>编辑</el-button>
						<el-button type="danger" size="mini" @click='delAdmin(scope.row)'>删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<!-- 添加或修改对话框 -->
			<el-dialog :title="title" :visible.sync="dialogVisible">
				<el-form ref="adminFrom" :rules="rules" :model="adminFrom" status-icon label-position="left" label-width="100px"
				 style="width: 400px; margin-left:50px;">
					<el-form-item label="登录名" prop="username">
						<el-input v-model="adminFrom.username" :disabled="title === '修改'"/>
					</el-form-item>
					<el-form-item label="密码" prop="password">
						<el-input v-model="adminFrom.password" type="password" auto-complete="off"/>
					</el-form-item>
					<el-form-item label="手机号" prop="phone">
						<el-input v-model="adminFrom.phone"/>
					</el-form-item>
					<el-form-item label="真实姓名" prop="realname">
						<el-input v-model="adminFrom.realname"/>
					</el-form-item>
					<el-form-item label="授权角色" prop="roleIds">
						<el-select v-model="adminFrom.roleIds" multiple placeholder="请选择">
							<el-option v-for="item in roleList" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</el-form-item>
				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button @click="closeDialog">取消</el-button>
					<el-button v-if="title === '创建'" type="primary" @click="createAdmin('adminFrom')">确定</el-button>
					<el-button v-else type="primary" @click="updateAdmin('adminFrom')">确定</el-button>
				</div>
			</el-dialog>
			<!-- 分页 -->
			<el-footer v-if="adminList.length>0" class="border-top d-flex align-items-center px-0  bg-white" style="margin-top: 36px;">
				<div style="flex: 1;" class="px-2">
					<el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="page.current"
					 :page-sizes="page.sizes" :page-size="page.size" layout="total, sizes, prev, pager, next, jumper" :total="page.total">
					</el-pagination>
				</div>
			</el-footer>

		</div>
	</div>
</template>
<script>
	import {
		admin,
		addAdmin,
		optionsRole,
		updateAdmin,
		deleteAdmin
	} from "../api.js"
	export default {
		data() {
			// 密码验证
			var validatePass = (rule, value, callback) => {
				let reg = /^[a-zA-Z0-9_-]{6,18}$/;
				if (value === '') {
					callback(new Error('密码不能为空'));
				} else if (!reg.test(value)) {
					callback(new Error('请输入字母、数字,长度不能少于6'));
				}
				callback();
			};
			// 手机号验证
			var validatePhone = (rule, value, callback) => {
				let regPhone = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
				if (value === '') {
					callback(new Error('手机号不能为空'));
				} else if (!regPhone.test(value)) {
					callback(new Error('请输入正确的手机号'));
				}
				callback();
			};
			// 真实姓名验证
			var validateName = (rule, value, callback) => {
				let regName = /^[\u4e00-\u9fa5]+$/
				if (value === '') {
					callback(new Error('真实姓名不能为空'));
				} else if (!regName.test(value)) {
					callback(new Error('真实姓名必须是中文'));
				}
				callback();
			};
			return {
				title: '创建', //对话框的标题
				searchVal: "",
				adminList: [], //管理员列表
				loading: true, //刷新
				page: { //分页
					current: 1,
					sizes: [10, 20, 30, 50, 100],
					size: 20,
					total: 1 //分页总条数
				},
				roleList: [],
				dialogVisible: false,
				rules: {
					//输入框验证规则
					username: [{
						required: true,
						message: "管理员名称不能为空",
						trigger: "blur"
					}],
					password: [{
						validator: validatePass,
						trigger: "blur"
					}],
					phone: [{
						validator: validatePhone,
						trigger: "blur"
					}],
					realname: [{
						validator: validateName,
						trigger: "blur"
					}]
				},
				adminFrom: {
					id: "",
					username: "",
					password: "",
					avatar: "",
					roleIds: []
				},
			}
		},
		methods: {
			// 获取数据
			getDate() {
				let _this = this;
				_this.loading = true;
				let page = {
					username: _this.searchVal,
					page: _this.page.current,
					limit: _this.page.size
				}
				admin(page).then((res) => {
					// console.log(res.data)
					_this.adminList = res.data.data.items;
					_this.loading = false;
					_this.page.total = res.data.data.total; //总条数
				})
			},
			// 搜索
			search() {
				this.page.total = 1;
				this.getDate()
			},
			handleSizeChange(val) { //每页条数
				this.page.size = val
				this.getDate();
			},
			handleCurrentChange(val) { //前往第几页
				this.page.current = val
				// console.log(val)
				this.getDate()
			},
			// 管理员角色
			getRole(roleId) {
				for (let i = 0; i < this.roleList.length; i++) {
					if (roleId === this.roleList[i].value) {
						return this.roleList[i].label;
					}
				}
			},
			// 初始化表单
			fixAdmin(type, value) {
				this.dialogVisible = true; //打开对话框
				if (type === 'add') { //判断是创建还是修改
					this.title = "创建"
					this.adminFrom = {
						id: "",
						username: "",
						password: "",
						avatar: "",
						roleIds: []
					}
				} else {
					this.title = "修改"
					this.adminFrom = Object.assign({}, value);
				}
				if (this.$refs.adminFrom != undefined) { //移除验证
					this.$refs.adminFrom.resetFields();
				}
			},
			// 关闭对话框
			closeDialog() {
				this.dialogVisible = false;
			},
			// 添加管理员
			createAdmin(formName) {
				let _this = this;
				this.$refs[formName].validate((valid) => {
					if (valid) {
						addAdmin(this.adminFrom).then((res) => {
							// console.log(res)
							if (res.data.errmsg === "管理员用户名重复") {
								_this.dialogVisible = false;
								_this.$message.error(res.data.errmsg);
								_this.getDate()
							} else {
								this.adminList.unshift(res.data.data);
								this.dialogVisible = false;
								this.page.total = this.page.total + 1;
								_this.$message.success("添加管理员成功")
							}
						})
					} else {
						return false;
					}
				})

			},
			// 编辑管理员
			updateAdmin(formName) {
				let _this = this;
				this.$refs[formName].validate((valid) => {
					if (valid) {
						updateAdmin(this.adminFrom).then((res) => {
							if (res.data.errno == 200) {
								_this.dialogVisible = false;
								_this.$message.success( "更新管理员成功")
								_this.getDate()
							} else {
								_this.dialogVisible = false;
								_this.$message.error(res.data.errmsg);
								_this.getDate()
							}
						})
					} else {
						return false;
					}
				})
			},
			// 删除
			delAdmin(value) {
				let _this = this;
				this.$confirm(
						"此操作将永久删除该管理员---" + value.username + "---, 是否继续?",
						"提示", {
							confirmButtonText: "确定",
							cancelButtonText: "取消",
							type: "warning"
						}
					)
					.then(() => {
						deleteAdmin(value.id).then((res) => {
							this.$message.success("删除管理员成功");
							let index = _this.adminList.indexOf(value);
							_this.adminList.splice(index, 1);
						})
					})

			}
		},
		created() {
			this.getDate()
			optionsRole().then((res) => { //获取管理员名称
				// console.log(res.data.data)
				this.roleList = res.data.data
			})
		},
	}
</script>

<style>
	.role_container {
		width: 100%;
		height: 660px;
		overflow-x: hidden;
		overflow-y: auto;
	}

	.role_section {
		padding: 20px;
		background-color: #fff;
		width: 100%;
		height: 100%;
	}

	.role_header {
		padding-bottom: 10px;
	}
	.el-form-item__content{
		width: 300px !important;
	}
</style>
